package droidplugin;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.RemoteException;
import android.os.storage.StorageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.example.qingyun.basefunction.MainActivity;
import com.example.qingyun.basefunction.R;
import com.morgoo.droidplugin.pm.PluginManager;
import com.morgoo.helper.compat.PackageManagerCompat;

import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import example.mono_tab.MonoActivity;
import example.mvpmode.splash.SplashActivity;

public class DroidPluginActivityTest extends AppCompatActivity {
    @BindView(R.id.tv_result)
    TextView tvResult;
    @BindView(R.id.install_result)
    TextView install_result;
    File[] plugins;
    public int index;
    private static String  TAG =DroidPluginActivityTest.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_droid_plugin_test);
        ButterKnife.bind(this);

    }

    //**参数 is_removable为false时得到的是内置sd卡路径，为true则为外置sd卡路径
    @OnClick({R.id.btn_install,R.id.start_plugin})
    public void doOnClick(View view) {
        switch (view.getId()){
            case  R.id.btn_install:
                getPermission();
                break;
            case  R.id.start_plugin:
                PackageManager pm =getPackageManager();
                Intent intent=pm.getLaunchIntentForPackage("coder.prettygirls");
                if (intent!=null){
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
                break;
        }
    }
    private void installApk() {
        File file=new File(Environment.getExternalStorageDirectory(),"/plugin/");
//        File test=new File(Environment.getExternalStorageDirectory()+"/plugin/app-debug.apk");
//        Log.i(TAG, test.getAbsolutePath());
        ;
//                File file=new File(getStoragePath(this,true),"/plugin");
        plugins=file.listFiles();
        if (plugins==null||plugins.length==0){

            Log.i(TAG,"没有找到插件");
            Log.i(TAG,file.getAbsolutePath());
            return;
        }
        // 1 .先卸载
        try {
            PluginManager.getInstance().deletePackage("coder.prettygirls",0);
        }catch (RemoteException e){
         e.printStackTrace();
    }
        for (File apk :plugins){
            if (!apk.getAbsolutePath().contains(".apk")){
                Log.i(TAG,"不是apk");
                continue;
            }

            try {
                tvResult.setText(apk.getAbsolutePath());
                index=PluginManager.getInstance().installPackage(apk.getAbsolutePath(), PackageManagerCompat.INSTALL_REPLACE_EXISTING);
                setInstallResult(index);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void setInstallResult(int index) {
        switch (index) {
            case -1:
                tvResult.setText("安装或卸载失败");
                break;
            case 1:
                tvResult.setText("安装或卸载成功");
                break;
            case -110:
                tvResult.setText("安装程序内部错误");
                break;
            case -2:
                tvResult.setText("无效的Apk");
                break;
            case 0x00000002:
                tvResult.setText("安装更新");
                break;
            case -3:
                tvResult.setText("不支持的ABI");
                break;

            default:
                tvResult.setText("老天都不知道这是咋了,");
                break;
        }
    }


    void getPermission()
    {
        int permissionCheck1 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE);
        int permissionCheck2 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck1 != PackageManager.PERMISSION_GRANTED || permissionCheck2 != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                    124);
        }
    }


    private static String getStoragePath(Context mContext, boolean is_removale) {

        StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
        Class<?> storageVolumeClazz = null;
        try {
            storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
            Object result = getVolumeList.invoke(mStorageManager);
            final int length = Array.getLength(result);
            for (int i = 0; i < length; i++) {
                Object storageVolumeElement = Array.get(result, i);
                String path = (String) getPath.invoke(storageVolumeElement);
                boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
                if (is_removale == removable) {
                    return path;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 124) {
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED))
            {
                Log.d("heihei","获取到权限了！");
                installApk();

            } else {
                Log.d("heihei","搞不定啊！");
            }
        }
    }

}
